package com.finalproject.ui;
/**
 * CardHolder for UI
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import com.finalproject.entity.CardHolder;
import com.finalproject.entity.CardHolderDatabase;
import com.finalproject.entity.DietaryEntry;
import com.finalproject.entity.DietaryProfile;
import com.finalproject.entity.DietaryProfile.DietaryProfileObserver;
import com.finalproject.entity.ExpenseProfile;
import com.finalproject.entity.ExpenseProfile.ExpenseProfileObserver;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;

public class UICardHolder extends JPanel implements CardHolderDatabase.CardHolderDatabaseObserver,ExpenseProfileObserver,DietaryProfileObserver{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private UIEnterCardHolder enterCardHolder;
	
	private UICardHolderInfo cardHolderInfo;
	public UICardHolder() {
		setLayout(new FlowLayout());
		setBorder(BorderFactory.createTitledBorder("CardHolder Panel"));
		CardHolderDatabase.getInstance().addCardHolderDatabaseObserver(this);
		enterCardHolder = new UIEnterCardHolder();
		enterCardHolder.getEnterButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JTextField accessCardNumberTextField = enterCardHolder.getAccessCardNumberTextField();
				JTextField pinCodeTextField = enterCardHolder.getAccessCodeTextField();
				JTextField familyIDTextField = enterCardHolder.getFamildyIdTextField();
				
				authenticate(accessCardNumberTextField.getText(), pinCodeTextField.getText(),familyIDTextField.getText());
				
				
			}
			
		});
		
		
		add(enterCardHolder);
		//ssaaa
	}
	
	
	public void authenticate(String accessCardNumberStr, String pincodeStr, String familyIdStr) {
		try {
			int accessCardNumber = Integer.parseInt(accessCardNumberStr);
			int pinCode = Integer.parseInt(pincodeStr);
			if(familyIdStr.isEmpty()) {
				familyIdStr = "00";
			}
			int familyId = Integer.parseInt(familyIdStr);
			CardHolderDatabase.getInstance().authenticate(accessCardNumber, pinCode,familyId);
			
		} catch(Exception e) {
			e.printStackTrace();
			UIHelper.showErrorMessage(this, "Invalid Access Card/pinCode/Family Id");
		}
		
	}
	
	
	
	public class UIEnterCardHolder extends JPanel {
		private JTextField accessCardNumberTextField;
		private JPasswordField accessCodeTextField;
		private JPasswordField familyIdTextField;
		private JButton enterButton;
		
		
		public UIEnterCardHolder() {
			super(new BorderLayout());
			DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(""));
	        builder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
	        builder.appendColumn("right:pref");
	        builder.appendColumn("3dlu");
	        builder.appendColumn("fill:max(pref; 100px)");
	        builder.appendColumn("5dlu");
	        builder.appendColumn("right:pref");
	        builder.appendColumn("3dlu");
	        builder.appendColumn("fill:max(pref; 100px)");
	        
//	        accessCardNumberTextField = new JTextField("123456");
//	        accessCodeTextField = new JPasswordField("1234");
//	        familyIdTextField = new JPasswordField("1");
	        
	        accessCardNumberTextField = new JTextField("");
	        accessCodeTextField = new JPasswordField("");
	        familyIdTextField = new JPasswordField("");
	        
	        builder.append("Access Card Number:", accessCardNumberTextField);
	        builder.nextLine();
	        builder.append("AccessCode:", accessCodeTextField);
	        builder.nextLine();
	        builder.append("Family ID:", familyIdTextField );
	        
	        builder.nextLine();
	        add(builder.getPanel(),BorderLayout.NORTH);
	        enterButton = new javax.swing.JButton("Swipe");
	        add(enterButton,BorderLayout.SOUTH);
		}
		
		private void reset() {
			accessCardNumberTextField.setText("");
			accessCodeTextField.setText("");
			familyIdTextField.setText("");
		}
		
		public JButton getEnterButton() {
			return enterButton;
		}
		
		
		public JTextField getAccessCardNumberTextField() {
			return accessCardNumberTextField;
		}
		
		public JPasswordField getAccessCodeTextField() {
			return accessCodeTextField;
		}
		
		public JPasswordField getFamildyIdTextField() {
			return familyIdTextField;
		}
	}





	@Override
	public void onLogin(CardHolder cardHolder, Integer familyId) {
		showCardHolderInfo(cardHolder,familyId);
		cardHolder.getExpense().addExpenseProfileObserver(this);
		cardHolder.getDietary().addDietaryProfileObserver(this);
	}


	@Override
	public void onLogout(CardHolder cardHolder, Integer familyId) {
		logout();
		cardHolder = null;
		
		enterCardHolder.reset();
	}
	
	
	public void showCardHolderInfo(final CardHolder cardHolder, final int familyId) {
		removeAll();
		this.cardHolderInfo = new UICardHolderInfo(cardHolder,familyId);
		this.cardHolderInfo.getLogOutButton().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				CardHolderDatabase.getInstance().logout(cardHolder, familyId);
			}
		});
		add(cardHolderInfo);
		
		revalidate();
		repaint();
		
	}
	
	public void logout() {
		removeAll();
		add(enterCardHolder);
		revalidate();
		repaint();
	}
	
	
	
	public class UICardHolderInfo extends JPanel {
		
		private JLabel availableFundLabel;
		private JLabel usedFundLabel;
		private JLabel alertLabel;
		private JLabel availableCaloriesLabel;
		private JLabel usedCaloriesLabel;
		private JButton logoutButton;
		private JLabel familyIdLabel;
		private JLabel exceededLabel;
		public UICardHolderInfo(CardHolder cardHolder, Integer familyId) {
			super(new BorderLayout());
			DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(""));
	        builder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
	        builder.appendColumn("right:pref");
	        builder.appendColumn("3dlu");
	        builder.appendColumn("fill:max(pref; 100px)");
	        builder.appendColumn("5dlu");
	        builder.appendColumn("right:pref");
	        builder.appendColumn("3dlu");
	        builder.appendColumn("fill:max(pref; 100px)");
			
			
			
			builder.append(new JLabel("Welcome " + cardHolder.getName()));
			builder.nextLine();
			
			if(familyId != 0) {
				builder.append(new JLabel("Family ID: " + familyId));
				builder.nextLine();
				
			}
			
			availableFundLabel = new JLabel();
			builder.append(availableFundLabel);
			builder.nextLine();
			
			usedFundLabel = new JLabel();
			builder.append(usedFundLabel);
			builder.nextLine();
			
			availableCaloriesLabel = new JLabel();
			builder.append(availableCaloriesLabel);
			builder.nextLine();
			
		
			usedCaloriesLabel = new JLabel();
			builder.append(usedCaloriesLabel);
			builder.nextLine();
			exceededLabel = new JLabel();
			builder.append(exceededLabel);
			
			
			builder.nextLine();
			logoutButton = new JButton("Exit");
			builder.append(logoutButton);
			setExpenseProfile(cardHolder.getExpense());
			setDietaryProfile(cardHolder.getDietary());
			
			
			
			add(builder.getPanel(),BorderLayout.CENTER);
			
		}
		
		public void setExpenseProfile(ExpenseProfile expense) {
			double fundsAvailable = expense.getFundsAvailable();
			double fundsUsed = expense.getFundsUsed();
			
			availableFundLabel.setText("My Available Fund is " + UIHelper.currencyFormat.format(fundsAvailable));
			usedFundLabel.setText("My Used Fund is " + UIHelper.currencyFormat.format(fundsUsed));
		}
		
		public void setDietaryProfile(DietaryProfile dietaryProfile) {
			int calories = dietaryProfile.getCalories();
			
			DietaryEntry last = dietaryProfile.getDietEntries().getLast();
			availableCaloriesLabel.setText("My Max Calories is "  + new Integer(calories).toString() + " cal");
			
			if(last != null) {
				Calendar lastDate = last.getDate();
				Calendar today = Calendar.getInstance();
				if ((today.get(Calendar.DAY_OF_MONTH)==lastDate.get(Calendar.DAY_OF_MONTH)) && (lastDate.get(Calendar.MONTH)==lastDate.get(Calendar.MONTH)) && (lastDate.get(Calendar.YEAR)==lastDate.get(Calendar.YEAR))){
					
					int usedCals=last.getConsumed();
					usedCaloriesLabel.setText("Today Used Calories is "  + new Integer(usedCals).toString() + " cal");
					
					int exceeded = Math.abs((dietaryProfile.getCalories() - usedCals));
					if ((usedCals>dietaryProfile.getCalories())) {
						exceededLabel.setText("Exceeded calories by " + exceeded + " cal");
						usedCaloriesLabel.setForeground(Color.RED);
						exceededLabel.setForeground(Color.RED);
					} else {
						usedCaloriesLabel.setForeground(Color.BLACK);
						exceededLabel.setText("");
						exceededLabel.setForeground(Color.BLACK);
					}
					
				} else {
					usedCaloriesLabel.setText("Today Used Calories is "  + new Integer(0).toString() + " cal");
					
				}
			}
			
		}
		
		
		
		
		public JButton getLogOutButton() {
			return logoutButton;
		}
	}





	
	@Override
	public void onUpdate(ExpenseProfile expenseProfile) {
		// TODO Auto-generated method stub
		cardHolderInfo.setExpenseProfile(expenseProfile);
	}


	@Override
	public void onUpdate(DietaryProfile dietaryProfile) {
		cardHolderInfo.setDietaryProfile(dietaryProfile);
		
		
				
		
		
		
	}
	
	
	
	
	
	
}
